package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import manager.Phase1;

import textEngine.SynonymousFinder;

import domain.RepresentationsNamesRecord;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class FindSynonymousServlet extends HttpServlet {
	
	/**
	 * Servlet che si occupa di gestire la richiesta di trovare i simili di un dato nome
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		long NID= Long.valueOf((String) req.getParameter("NID")); 
		System.out.println("Avviata FindSynonymousServlet per NID:"+NID);
		long startTime = System.currentTimeMillis();
		List<RepresentationsNamesRecord> sinonimiTrovati=SynonymousFinder.findSynonymous(NID);
	
		resp.setContentType("text/xml; charset=UTF-8");
	    PrintWriter out = resp.getWriter();   
	    out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
	    
	    if (sinonimiTrovati!=null){
	    	out.println("<sinonimi>");
			for (RepresentationsNamesRecord sinonimo : sinonimiTrovati) {
				out.println("\t<sinonimo>");
				out.println("\t\t<NID>"+sinonimo.getNID()+"</NID>");
				out.println("\t\t<Value>"+sinonimo.getValue()+"</Value>");
				out.println("\t\t<representativeNID>"+sinonimo.getRepresentativeNID()+"</representativeNID>");
				out.println("\t\t<isBlackListed>"+sinonimo.getIsBlackListed()+"</isBlackListed>");
				out.println("\t</sinonimo>");
			}
			out.println("</sinonimi>");
	    }
	    else{
	    	out.print("\n<sinonimi></sinonimi>");	
	    }
	    long endTime = System.currentTimeMillis();
	    System.out.println("\tSinonimi calcolati in "+(endTime-startTime)+" ms\n");
	    sinonimiTrovati=null; //libero memoria
	    out.flush();
	}

}

